<template>
  <view class="activity-registration">
    <div class="dadwafgada" style="padding-top: 48px; display: flex; justify-content: center">
      <text class="awdawdfa">{{ baoming ? "修改报名" : "活动报名" }}</text>
    </div>
    <!-- 表单区域 -->
    <view class="form-container">
      <u-form labelPosition="left" labelWidth="150" :model="form" ref="uForm">
        <!-- 姓名 -->
        <u-form-item label="姓名" prop="applicationName" required>
          <u-input v-model="form.applicationName" placeholder="请输入您的姓名" border="bottom"></u-input>
        </u-form-item>

        <!-- 手机号 -->
        <u-form-item label="手机号" prop="applicationPhone" required>
          <u-input v-model="form.applicationPhone" placeholder="请输入您的手机号" type="number" maxlength="11" border="bottom"></u-input>
        </u-form-item>

        <!-- 个人照片上传 -->
        <u-form-item label="个人照片" prop="applicationAvatar" required>
          <u-upload :fileList="avatarList" @afterRead="afterReadAvatar" @delete="deleteAvatar" :maxCount="1" width="160rpx" height="160rpx" name="applicationAvatar" multiple>
            <u-button size="mini" type="primary" plain icon="plus">上传头像</u-button>
          </u-upload>
        </u-form-item>

        <!-- 相关图片上传 -->
        <u-form-item label="相关图片" prop="applicationCarousel">
          <u-upload :fileList="imageList" @afterRead="afterReadImage" @delete="deleteImage" multiple :maxCount="9" width="140rpx" height="140rpx" name="applicationCarousel">
            <u-button size="mini" type="primary" plain icon="plus">上传</u-button>
          </u-upload>
        </u-form-item>

        <!-- 音乐文件上传 -->
        <u-form-item label="音乐文件" prop="applicationMusic">
          <u-upload :fileList="musicList" @afterRead="afterReadMusic" @delete="deleteMusic" :maxCount="1" width="140rpx" height="140rpx" name="applicationMusic" :accept="'audio/*'">
            <u-button size="mini" type="primary" plain icon="plus">上传音乐</u-button>
          </u-upload>
        </u-form-item>

        <!-- 个人简介（富文本） -->
        <u-form-item label="报名才艺" prop="applicationRemark" required>
          <u--textarea v-model="form.applicationRemark" placeholder="请输入" autoHeight border="bottom" :autoSize="{ minRows: 2, maxRows: 6 }"></u--textarea>
        </u-form-item>
        <!-- 选择字典上台表演时间 -->
        <!-- 选择字典上台表演时间 -->
        <u-form-item label="上台表演时间" prop="applicationShowTime" required>
          <!-- 循环timeList单选 -->
          <u-radio-group placement="row" v-model="form.applicationShowTime" wrap>
            <view style="display: flex; flex-wrap: wrap">
              <u-radio
                size="30"
                iconSize="20"
                labelSize="30"
                v-for="(item, index) in timeList"
                :name="item.dictLabel"
                :key="index"
                :customStyle="{ marginRight: '10px', marginBottom: '10px' }"
              >
                {{ item.dictLabel }}
              </u-radio>
            </view>
          </u-radio-group>
        </u-form-item>
        <!-- 附加信息 -->
        <u-form-item label="附加信息" prop="applicationIllustrate">
          <u--textarea v-model="form.applicationIllustrate" placeholder="如有其他需要说明的信息，请在此填写" autoHeight border="bottom" :autoSize="{ minRows: 2, maxRows: 6 }"></u--textarea>
        </u-form-item>
        <!-- 提交按钮 -->
        <view class="submit-button-container">
          <u-button type="primary" shape="circle" @click="submitForm" :loading="submitLoading">{{ baoming ? "修改报名" : "提交报名" }}</u-button>
        </view>
      </u-form>
    </view>
    <u-popup :show="isShow" :round="10" mode="bottom">
      <view style="padding: 20px 20px 20px 20px">
        <!-- <div style="float: right; color: #999; font-size: 12px" >暂不设置</div> -->
        <div style="font-weight: bold; margin-top: 15px; letter-spacing: 1.5px">设置您的昵称与头像</div>
        <div style="font-size: 12px; padding: 5px 0px 10px 0px; border-bottom: 1px solid #ededed">用户抽奖奖品兑换认证</div>
        <div style="display: flex; height: 60px; font-size: 13px; align-items: center; border-bottom: 1px solid #ededed">
          <div style="width: 60px">头像</div>
          <div>
            <button open-type="chooseAvatar" class="dawdaw" @chooseavatar="onChooseAvatar">
              <image :src="newAvatar.indexOf('http') != -1 ? newAvatar : IMG_URL + newAvatar" style="width: 40px; height: 40px"></image>
            </button>
          </div>
        </div>
        <div style="display: flex; height: 60px; font-size: 13px; align-items: center; border-bottom: 1px solid #ededed">
          <div style="width: 60px">昵称</div>
          <div>
            <input type="nickname" v-model="nickname" placeholder="请输入昵称" />
          </div>
        </div>
        <div style="margin-top: 15px; display: flex; justify-content: center">
          <button class="dawdjnhuhie" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">保 存</button>
        </div>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { IMG_URL } from "../../../config/index";
import { application, applicationList, applicationEdit /* 报名修改 */ } from "../../../utils/api/vote";
import { programlogin, phoneAndPassword, getUserInfo, getUserPhoneNumber, newUserIntegral } from "../../../utils/request_api.js";
import { userEdit } from "../../../utils/api/local";
import { notBindingPhone } from "../../../utils/api/api.js";
import { getDicts } from "../../../utils/request_sh";
export default {
  data() {
    return {
      timeList: "",
      activeid: "",
      IMG_URL,
      nickname: "微信用户",
      newAvatar: "https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/03/20/f_20250320164147A002.png",
      isShow: false,
      submitLoading: false,
      avatarList: [],
      imageList: [],
      musicList: [], // 添加音乐文件列表
      baoming: false, // 添加baoming变量用于判断是否已报名
      form: {
        applicationName: "",
        applicationPhone: "",
        applicationAvatar: "", // 添加avatar字段用于表单校验
        applicationCarousel: "", // 添加images字段用于存储相关图片文件名
        applicationMusic: "", // 添加音乐文件字段
        applicationMusicName: "", // 添加音乐文件名字段
        applicationRemark: "",
        applicationIllustrate: "",
        ebUserId: uni.getStorageSync("uid"),
        ebVoteActivityId: "",
        activeName: "",
      },
      rules: {
        applicationName: [
          {
            required: true,
            message: "请输入姓名",
            trigger: ["blur", "change"],
          },
        ],
        applicationPhone: [
          {
            required: true,
            message: "请输入手机号",
            trigger: ["blur", "change"],
          },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "手机号格式不正确",
            trigger: ["blur", "change"],
          },
        ],

        applicationAvatar: [
          {
            required: true,
            message: "请上传个人照片",
            trigger: ["blur", "change"],
          },
        ],
        applicationRemark: [
          {
            required: true,
            message: "请输入个人简介",
            trigger: ["blur", "change"],
          },
        ],
      },
      imgUrl: IMG_URL,
    };
  },
  /* 分享到朋友和朋友圈 */
  /*   onShareAppMessage() {
    return {
      title: "我在参加 " + this.activeName + " ,请为我投票",
      path: "/pages_h5/myCenter/components/votelist",
    };
  }, */
  /*   mounted() {
    let storedOpenID = uni.getStorageSync("openID");
    if (storedOpenID) {
      this.initUser();
    } else {
      this.autoLogin();
    }
  }, */
  onReady() {
    // 设置表单验证规则
    this.$refs.uForm.setRules(this.rules);
  },
  onLoad(options) {
    this.getZidian();
    this.activeid = options.activeid;
    this.activeName = options.activeName;
    this.form.ebVoteActivityId = this.activeid;
    this.$nextTick(() => {
      this.initUser();
      // this.logggggin();
      // this.handleClose();
      // this.showloginJs();
    });
  },
  methods: {
    getZidian() {
      getDicts("bmsj")
        .then((response) => {
          this.timeList = response.data;
        })
        .catch((error) => {
          console.error("获取字典数据失败:", error);
        });
    },
    getaplicationList() {
      applicationList({ ebUserId: uni.getStorageSync("uid"), ebVoteActivityId: this.activeid }).then((res) => {
        if (res.code == 200) {
          if (res.rows.length > 0) {
            this.baoming = true;
            // 如果已报名，填充表单数据
            const data = res.rows[0];
            this.form = {
              ...this.form,
              applicationName: data.applicationName,
              applicationPhone: data.applicationPhone,
              applicationAvatar: data.applicationAvatar,
              applicationCarousel: data.applicationCarousel,
              applicationMusic: data.applicationMusic, // 添加音乐文件数据
              applicationMusicName: data.applicationMusicName, // 添加音乐文件名数据
              applicationRemark: data.applicationRemark,
              applicationIllustrate: data.applicationIllustrate,
              applicationShowTime: data.applicationShowTime,
              id: data.id, // 保存报名记录ID用于修改
            };

            // 处理头像显示
            if (data.applicationAvatar) {
              this.avatarList = [
                {
                  url: this.imgUrl + data.applicationAvatar,
                  fileName: data.applicationAvatar,
                  status: "success",
                },
              ];
            }

            // 处理相关图片显示
            if (data.applicationCarousel) {
              const images = data.applicationCarousel.split(",");
              this.imageList = images.map((img) => ({
                url: this.imgUrl + img,
                fileName: img,
                status: "success",
              }));
            }

            // 处理音乐文件显示
            if (data.applicationMusic) {
              this.musicList = [
                {
                  url: this.imgUrl + data.applicationMusic,
                  fileName: data.applicationMusic,
                  name: data.applicationMusicName || "音乐文件",
                  status: "success",
                },
              ];
            }
          }
        }
      });
    },
    initUser() {
      uni.showLoading();
      getUserInfo()
        .then((res) => {
          if (res.code === 401) {
            this.showloginJs();
          } else {
            this.userInfo = res.data;
            uni.setStorageSync("userInfo", res.data);
            this.getaplicationList();
            this.aaaa = true;
            uni.hideLoading();
            this.showzhezhao = false;
          }
        })
        .catch((err) => {
          console.error("获取用户信息失败", err);
          uni.hideLoading();
        });
    },
    showloginJs() {
      let that = this;
      uni.login({
        provider: "weixin",
        success: (res) => {
          if (res.code) {
            that.autoLogin(res.code);
          } else {
            uni.hideLoading();
            console.error("登录失败:", res.errMsg);
            uni.showToast({
              title: "微信登录失败，请稍后再试",
              icon: "none",
            });
          }
        },
        fail: (err) => {
          console.error("登录失败:", err);
          uni.showToast({
            title: "微信登录失败，请稍后再试",
            icon: "none",
          });
        },
      });
      // let storedOpenID = uni.getStorageSync("openID");
      // if (storedOpenID) {
      //   this.authKey = storedOpenID;
      //   this.initUser();
      // } else {

      // }
    },
    /* 免登录-每个界面调用 */
    async autoLogin(code) {
      let that = this;
      wx.getUserInfo({
        success(res) {
          const { nickName, avatarUrl, gender } = res.userInfo;
          programlogin({ code, avatar: avatarUrl, nickName, sex: gender }).then((response) => {
            const data = response.data;
            console.log("🚀 ~ programlogin ~ data:", data);
            that.authKey = data.key;
            that.openIdadw = data.openId;
            if (data.type === "login") {
              uni.setStorageSync("uid", data.uid);
              uni.setStorageSync("token", data.token);
              uni.setStorageSync("userInfo_data", data);
              uni.setStorageSync("openID", data.key);
              that.initUser();
              uni.hideLoading();
            } else {
              that.initUserregister();
            }
          });
        },
        fail: () => {
          uni.showToast({
            title: "您需要授权，才能获取您的信息！",
          });
        },
      });
    },
    initUserregister() {
      var params = {
        key: this.authKey,
        type: "routine",
        openId: this.openIdadw,
        phone: "",
        password: "",
        captcha: "",
        codeOrPassword: "3",
        inviterLinkId: "",
      };
      notBindingPhone(params).then((res) => {
        uni.hideLoading();
        if (res.code == 200) {
          const data = res.data;
          uni.setStorageSync("uid", data.uid);
          uni.setStorageSync("token", data.token);
          uni.setStorageSync("userInfo_data", data);
          uni.setStorageSync("openID", this.authKey);
          this.isShow = true;
          this.initUser();
        }
      });
    },
    onChooseAvatar(e) {
      console.log(e);
      var that = this;
      uni.uploadFile({
        url: "https://www.wantongkonggu.cn//api/frontApph7/frontCommon/uploadTuPian?model=maintain&pid=0",
        filePath: e.detail.avatarUrl,
        name: "multipart",
        formData: {
          model: "maintain",
          pid: 0,
        },
        success: function (uploadRes) {
          const data = JSON.parse(uploadRes.data);
          that.$set(that, "newAvatar", data.fileName);
        },
        fail: function (err) {
          console.error("上传失败", err);
        },
      });
    },
    getPhoneNumber(e) {
      if (e.detail.code && e.detail.errMsg == "getPhoneNumber:ok") {
        getUserPhoneNumber(e.detail).then((res) => {
          if (res.code == 200 && res.data.errmsg == "ok") {
            let that = this;
            this.account = res.data.phone_info.phoneNumber;
            this.form.applicationPhone = this.account;
            this.awdawgawdgrr();
            this.isShow = false;
          } else {
            console.log("🚀 ~ getPhoneNumber ~ res:", res);
            uni.showToast({
              title: res.message,
              icon: "none",
            });
          }
        });
      }
    },
    awdawgawdgrr() {
      if (this.nickname == "") {
        uni.showToast({
          icon: "none",
          title: "请填写完整！",
        });
        return;
      }
      var params = {
        avatar: this.newAvatar,
        nickname: this.nickname,
        account: this.account,
        phone: this.account,
      };
      userEdit(params).then((res) => {
        this.initUser();
      });
    },
    editUser() {
      userEdit(value).then((res) => {
        if (res.code == 200) {
          uni.showToast({
            title: "修改成功",
          });
          setTimeout(() => {
            uni.navigateBack({
              delta: 1,
              animationType: "pop-out",
              animationDuration: 200,
            });
          }, 1500);
        }
      });
    },

    /*     gotoLogin() {
      var params = {
        phone: this.account,
        password: "",
        captcha: "",
        key: this.authKey,
        type: "routine",
        codeOrPassword: "3",
        inviterLinkId: "",
        inviteeType: "",
      };
      phoneAndPassword(params).then((res1) => {
        if (res1.code == 200) {
          uni.setStorageSync("userInfo_data", res1.data);
          this.uid = res1.data.uid;
          uni.setStorageSync("uid", res1.data.uid);
          uni.setStorageSync("token", res1.data.token);
          uni.setStorageSync("openID", res1.data.key);
          this.initUser();
          this.awdawgawdgrr();
          this.isShow = false;
        }
      });
    }, */

    // 个人照片读取后处理
    async afterReadAvatar(event) {
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file);
      let fileListLen = this.avatarList.length;

      lists.map((item) => {
        this.avatarList.push({
          ...item,
          status: "uploading",
          message: "上传中",
        });
      });

      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].url, 1);
        let item = this.avatarList[fileListLen];
        this.avatarList.splice(
          fileListLen,
          1,
          Object.assign(item, {
            status: "success",
            message: "",
            fileName: result, // 使用fileName而不是url
          }),
        );
        // 同时更新表单中的avatar字段，用于校验
        this.form.applicationAvatar = result;
        fileListLen++;
      }
    },

    // 图片读取后处理
    async afterReadImage(event) {
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file);
      let fileListLen = this.imageList.length;

      lists.map((item) => {
        this.imageList.push({
          ...item,
          status: "uploading",
          message: "上传中",
        });
      });

      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].url, 2);
        let item = this.imageList[fileListLen];
        this.imageList.splice(
          fileListLen,
          1,
          Object.assign(item, {
            status: "success",
            message: "",
            fileName: result, // 使用fileName而不是url
          }),
        );
        fileListLen++;
      }

      // 更新表单中的images字段，将所有图片fileName用逗号连接
      this.form.applicationCarousel = this.imageList.map((img) => img.fileName).join(",");
    },

    // 音乐文件读取后处理
    async afterReadMusic(event) {
      console.log("🚀 ~ event:", event);
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file);
      let fileListLen = this.musicList.length;

      lists.map((item) => {
        this.musicList.push({
          ...item,
          status: "uploading",
          message: "上传中",
        });
      });

      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].url, 3); // 使用不同的参数标识音乐文件
        let item = this.musicList[fileListLen];
        this.musicList.splice(
          fileListLen,
          1,
          Object.assign(item, {
            status: "success",
            message: "",
            fileName: result, // 使用fileName而不是url
            name: lists[i].name || "音乐文件", // 显示文件名
          }),
        );
        // 同时更新表单中的music字段
        this.form.applicationMusic = result;
        // 同时更新音乐文件名字段
        this.form.applicationMusicName = lists[i].name || "未知音乐文件";
        console.log("🚀 ~   this.form.applicationMusicName:", this.form.applicationMusicName);
        fileListLen++;
      }
    },

    uploadFilePromise(url, aa) {
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: "https://www.wantongkonggu.cn/api/adminApph7/common/upload", // 上传接口地址
          filePath: url,
          name: "file",
          formData: {},
          success: (res) => {
            try {
              const data = JSON.parse(res.data);
              if (data.code === 200) {
                setTimeout(() => {
                  resolve(data.fileName);
                }, 1000);
              } else {
                reject(new Error(data.msg || "上传失败"));
              }
            } catch (error) {
              console.error("解析响应数据失败:", error);
              console.error("服务器返回的原始数据:", res.data);
              reject(new Error("服务器响应格式错误"));
            }
          },
          fail: (err) => {
            console.error("上传失败:", err);
            reject(err);
          },
        });
      });
    },

    // 删除个人照片
    deleteAvatar(event) {
      this.avatarList.splice(event.index, 1);
      // 删除图片时同时清空表单中的avatar字段
      this.form.applicationAvatar = "";
    },

    // 删除图片
    deleteImage(event) {
      this.imageList.splice(event.index, 1);
      // 更新表单中的images字段
      this.form.applicationCarousel = this.imageList.map((img) => img.fileName).join(",");
    },

    // 删除音乐文件
    deleteMusic(event) {
      this.musicList.splice(event.index, 1);
      // 删除音乐文件时同时清空表单中的music字段和音乐名字段
      this.form.applicationMusic = "";
      this.form.applicationMusicName = "";
    },

    // 提交表单
    submitForm() {
      this.$refs.uForm
        .validate()
        .then(() => {
          this.submitLoading = true;
          if (this.baoming) {
            // 如果已报名，执行修改操作
            const editForm = { ...this.form };
            applicationEdit(editForm).then((res) => {
              if (res.code == 200) {
                setTimeout(() => {
                  this.submitLoading = false;
                  uni.showToast({
                    title: "修改成功",
                    icon: "none",
                  });
                }, 1500);
                uni.navigateTo({ url: "/pages_h5/myCenter/components/votelist" });
              } else {
                uni.showToast({
                  title: "修改失败，请稍后再试~",
                  icon: "none",
                });
                this.submitLoading = false;
              }
            });
          } else {
            this.form.ebUserId = uni.getStorageSync("uid");
            // 如果未报名，执行报名操作
            application(this.form).then((res) => {
              if (res.code == 200) {
                setTimeout(() => {
                  this.submitLoading = false;
                  uni.showToast({
                    title: "报名成功",
                    icon: "none",
                  });
                  uni.navigateTo({ url: "/pages_h5/myCenter/components/votelist" });
                  // 重置表单
                  this.getaplicationList();
                }, 1500);
              } else {
                uni.showToast({
                  title: "活动太火爆啦,请稍后再试~",
                  icon: "none",
                });
                this.submitLoading = false;
              }
            });
          }
        })
        .catch((errors) => {
          this.submitLoading = false;
          uni.showToast({
            title: "请检查填写内容",
            icon: "none",
          });
        });
    },

    // 重置表单
    resetForm() {
      this.form = {
        applicationName: "",
        applicationPhone: "",
        applicationAvatar: "", // 重置avatar字段
        applicationCarousel: "", // 重置images字段
        applicationMusic: "", // 重置音乐文件字段
        applicationMusicName: "", // 重置音乐文件名字段
        applicationRemark: "",
        applicationIllustrate: "",
        ebUserId: uni.getStorageSync("uid"),
        ebVoteActivityId: this.activeid,
      };
      this.avatarList = [];
      this.imageList = [];
      this.musicList = []; // 重置音乐文件列表
      this.baoming = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.activity-registration {
  background-image: url(http://www.wantongkonggu.cn/crmebimage/profile/upload/2025/10/21/9999_20251021093524A047.png);
  position: relative;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  min-height: 100vh;
  .form-container {
    width: 90%;
    min-height: 360px;
    border: 2px solid #fcdc5f;
    background-color: #fff;
    background-size: 100% 100%;
    background-repeat: no-repeat;
    margin: 0 auto;
    padding: 40rpx 10rpx 30rpx 30rpx;
    border-radius: 20rpx;
    position: relative;
    margin-top: 200rpx;
    box-sizing: border-box;
    ::v-deep .u-form-item {
      /*       margin-bottom: 20rpx; */
      padding: 0;
      position: relative;

      &__body {
        &__left {
          font-size: 28rpx;
          color: #333;
          margin-bottom: 8rpx;
        }

        &__right {
          .u-input,
          .u--textarea {
            border-radius: 8rpx;
            padding: 15rpx;
            font-size: 26rpx;
          }
        }

        &__right__message {
          font-size: 22rpx;
          color: #f00;
        }
      }
    }

    .submit-button-container {
      display: flex;
      justify-content: center;
      margin-top: 40rpx;

      ::v-deep .u-button {
        width: 70%;
        font-size: 30rpx;
        height: 80rpx;
      }
    }
  }
}
.dadwafgada {
  transform: rotate(-5deg);
}
.awdawdfa {
  font-family: "ruizhi";
  font-size: 40px;
  color: #fff;
  letter-spacing: 5px;
  text-stroke: 4px #f92a4c;
  color: transparent;
  -webkit-background-clip: text;
  background-image: linear-gradient(to top, #fff, #fdff6e);
}
</style>
